import axios from 'axios'
import { useUserStore } from '@/stores'

const IMAGE_URL = import.meta.env.VITE_IMAGE_URL

const request = axios.create({
  baseURL: import.meta.env.VITE_SERVE,
  timeout: 6000 * 2,
})

request.interceptors.request.use((config) => {
  const userStore = useUserStore()

  if (userStore.token) {
    config.headers['Authorization'] = userStore.token
  }

  // 在发送请求之前做些什么
  return config
})

request.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    if (response.data.code !== 200) {
      ElNotification({
        type: 'error',
        message: response.data.message,
      })
      return Promise.reject(response.data)
    }
    return response.data
  },
  (err) => {
    console.log('err');

    // 对响应错误做点什么
    let msg = err.response?.data?.message
    const status = err?.response?.status
    switch (status) {
      case 400:
        msg ??= '请求错误'
        break
      case 401:
        msg ??= '未授权，请重新登录'
        break
      case 403:
        msg ??= '拒绝访问'
        break
      case 404:
        msg ??= '请求地址错误'
        break
      case 500:
        msg ??= '服务器内部错误'
        break
      default:
        msg ??= '未知错误'
        break
    }
    ElMessage.error(msg)
    if (status === 401) {
      const userStore = useUserStore()
      const router = useRouter()
      userStore.logout()
      router.push('/login')
    }
    return Promise.reject(err)
  },
)

export default request

export {
  IMAGE_URL
}